// AESUtil.js
import CryptoJS from 'crypto-js'

const ALGORITHM = 'AES/CBC/PKCS7'
const SECRET_KEY_ALGORITHM = 'PBKDF2WithHmacSHA256'
const KEY_LENGTH = 128
const ITERATION_COUNT = 65536
const SALT_LENGTH = 16
const IV_LENGTH = 16

export function encrypt(plaintext, password = 'yykj!') {
  try {
    const salt = CryptoJS.lib.WordArray.random(SALT_LENGTH)
    const key = generateSecretKey(password, salt)
    const iv = CryptoJS.lib.WordArray.random(IV_LENGTH)

    const cipherText = CryptoJS.AES.encrypt(plaintext, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    })

    const combined = salt.concat(iv).concat(cipherText.ciphertext)
    return CryptoJS.enc.Base64.stringify(combined)
  } catch (e) {
    throw new Error('加密失败', e)
  }
}

export function decrypt(ciphertext, password = 'yykj!') {
  try {
    const combined = CryptoJS.enc.Base64.parse(ciphertext)
    const salt = CryptoJS.lib.WordArray.create(combined.words.slice(0, SALT_LENGTH / 4))
    const iv = CryptoJS.lib.WordArray.create(combined.words.slice(SALT_LENGTH / 4, (SALT_LENGTH + IV_LENGTH) / 4))
    const encrypted = CryptoJS.lib.WordArray.create(combined.words.slice((SALT_LENGTH + IV_LENGTH) / 4))

    const key = generateSecretKey(password, salt)
    const decrypted = CryptoJS.AES.decrypt({ ciphertext: encrypted }, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    })

    return decrypted.toString(CryptoJS.enc.Utf8)
  } catch (e) {
    throw new Error('解密失败', e)
  }
}

function generateSecretKey(password, salt) {
  const key = CryptoJS.PBKDF2(password, salt, {
    keySize: KEY_LENGTH / 32,
    iterations: ITERATION_COUNT,
  })
  return key
}
